package com.hnl.action.attachment;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Vector;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hnl.dao.AttachmentDAO;
import com.hnl.dao.DAOException;
import com.hnl.dao.HNLDAOFactory;
import com.hnl.to.Attachment;

@SuppressWarnings("serial")
@Deprecated
public class FileDownloadServlet extends HttpServlet {
	public static final Logger LOG = LoggerFactory
			.getLogger(FileDownloadServlet.class);

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ServletOutputStream op = resp.getOutputStream();

		try {
			AttachmentDAO attachmentDAO = HNLDAOFactory.getDAOFactory(
					HNLDAOFactory.HNLDAOFACTORY).getAttachmentDAO();

			Vector<Attachment> attachmentCollection = (Vector<Attachment>) attachmentDAO
					.loadAttachement(1);
			String filename = attachmentCollection.get(0).getSystemPath();

			File f = new File(filename);
			int length = 0;
			ServletContext context = getServletConfig().getServletContext();
			String mimetype = context.getMimeType(filename);

			resp.setContentType((mimetype != null) ? mimetype
					: "application/octet-stream");
			resp.setContentLength((int) f.length());
			resp.setHeader("Content-Disposition",
					"attachment; filename=\"" + f.getName() + "\"");

			DataInputStream in = new DataInputStream(new FileInputStream(f));

			while ((in != null) && ((length = in.read()) != -1)) {
				op.write(length);
			}
			in.close();
		} catch (DAOException e) {
			LOG.error("Error retrieving attachmentDAO.", e);
		} finally {
			op.flush();
			op.close();
		}

	}
}
